package 反射.代理模式.动态代理;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface Subject{
    public void request();
    public void say();
}

class ReaSubject implements Subject{

    @Override
    public void request() {
        System.out.println("I am reaSubject!");
    }

    @Override
    public void say() {
        System.out.println("say hello!");
    }
}
interface Subject2{
    public void cry();
}

class ReaSubject2 implements Subject2{

    @Override
    public void cry() {
        System.out.println("I am crying!");
    }

}

class MyInvocation implements InvocationHandler{

    Object subject;
    public MyInvocation(Object subject){
        this.subject = subject;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.println("before");
        Object res = method.invoke(subject,args);
        System.out.println("after");
        return res;
    }
}

public class DynamicProxyDemo {
    public static void main(String[] args) {
        ReaSubject reaSubject = new ReaSubject();
        MyInvocation myInvocation = new MyInvocation(reaSubject);
        Subject proxy = (Subject)Proxy.newProxyInstance(ReaSubject.class.getClassLoader(),ReaSubject.class.getInterfaces(),myInvocation);
        proxy.request();
        ReaSubject2 reaSubject2 = new ReaSubject2();
        myInvocation = new MyInvocation(reaSubject2);
        Subject2 proxy2 = (Subject2) Proxy.newProxyInstance(ReaSubject2.class.getClassLoader(),reaSubject2.getClass().getInterfaces(),myInvocation);
        proxy2.cry();
    }
}
